package controllers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class Helper {
	static private final SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd");
	static private final SimpleDateFormat DatetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	static public String dateToString(Date date) {
		try {
			return DateFormat.format(date);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	static public String datetimeToString(Date date) {
		try {
			return DatetimeFormat.format(date);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	static public Date stringToDate(String s) {
		try {
			Date d = (Date)DateFormat.parseObject(s);
			return d;
		} catch (ParseException e) {
			e.printStackTrace();
			return new Date();
		}
	}
	
	static public Date stringToDatetime(String s) {
		try {
			if (s.length() == 10) { //10 = length of ('2103-11-01')
				s = s + " 00:00:00";
			}
			
			//s = s.substring(0, 16); //去掉秒
			
			Date d = (Date)DatetimeFormat.parseObject(s);
			return d;
		} catch (ParseException e) {
			e.printStackTrace();
			return new Date();
		}
	}
	
	static public String getTodayStr() {
		return dateToString(new Date());
	}
	
	static public String getSelectOptionJson(String str) {
		String[] list = str.split("\\|");
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		for(int i =0; i<list.length; i++) {
			sb.append("\"");
			sb.append(list[i]);
			sb.append("\":\"");
			sb.append(list[i]);
			sb.append("\"");
			if (i != list.length - 1) {
				sb.append(",");
			}
		}
		sb.append("}");
		return sb.toString();		
	}
	
	static public Object stringToObject(String type, String value) {
		if (type.equalsIgnoreCase("Integer")) {
			return Integer.parseInt(value);
		} else if (type.equals("Date")) {
			return Helper.stringToDate(value);
		} else {
			return value;
		}
	}
}
